package com.youlu.campus.admin.community.controller;

import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityAutoTask;
import com.youlu.campus.entity.VO.req.ActivityAutoTaskQueryVO;
import com.youlu.campus.service.activity.ActivityAutoTaskService;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
public class ActivityAutoTaskController {
    @Autowired
    private ActivityAutoTaskService activityAutoTaskService;

    @PostMapping("/activity/auto-task/list")
    public QResult list(@RequestBody ActivityAutoTaskQueryVO req) {
        req.setOptUserId(AuthUtils.getUserId());
        return QResult.success(activityAutoTaskService.list(req));
    }

    @PostMapping("/activity/auto-task/create")
    public QResult create(@RequestBody ActivityAutoTask req) {
        req.setOptUserId(AuthUtils.getUserId());
        req.setOptUserName(AuthUtils.getLoginName());
        return QResult.success(activityAutoTaskService.create(req));
    }

    @PostMapping("/activity/auto-task/update")
    public QResult update(@RequestBody ActivityAutoTask req) {
        this.checkOwner(AuthUtils.getUserId(),req.getId());
        return QResult.success(activityAutoTaskService.update(req));
    }

    @GetMapping("/activity/auto-task/find-one")
    public QResult findOne(@RequestParam("id") String id) {
        this.checkOwner(AuthUtils.getUserId(),id);
        return QResult.success(activityAutoTaskService.findOne(id));
    }

    @GetMapping("/activity/auto-task/run")
    public QResult run(@RequestParam("id") String id) {
        this.checkOwner(AuthUtils.getUserId(),id);
        return QResult.success(activityAutoTaskService.run(id));
    }

    @GetMapping("/activity/auto-task/delete")
    public QResult delete(@RequestParam("id") String id) {
        this.checkOwner(AuthUtils.getUserId(),id);
        return QResult.success(activityAutoTaskService.delete(id));
    }

    @GetMapping("/activity/auto-task/withdraw")
    public QResult withdraw(@RequestParam("id") String id) {
        this.checkOwner(AuthUtils.getUserId(),id);
        return QResult.success(activityAutoTaskService.withdraw(id));
    }

    private void checkOwner(String userId, String id) {
        ActivityAutoTask req= activityAutoTaskService.findOne(id);
        if(!userId.equals(req.getOptUserId())){
            log.error(":>>> 当前用户非任务所有者:无操作权限:{},--{}",userId,req.getOptUserId());
            throw new BusinessException("当前用户非任务所有者:无操作权限");
        }
    }


}
